import { observable, action } from 'mobx';
import { Toast, Tools } from 'weaver-mobile';
import { ListViewPage } from 'weaver-mobile-page';

import Api, { getMailTemplate } from '../../apis/setting';

const getLabel = Tools.getLabel;

const initState = {
  template: { default: [{ key: 'col', configs: [{ key: 'col_row', configs: [{ key: 'name' }] }] }] },
  listParams: {
    url: getMailTemplate,
    params: {},
  },
  templateName: '',
  templateHtml: '',
};

export default class MailTemplate {

  template = initState.template;
  listParams = initState.listParams;

  @observable listViewStore = new ListViewPage.Store();
  @observable templateName = initState.templateName;
  @observable templateHtml = initState.templateHtml;

  @action
  getData = (params = { url: '', params: {} }, current) => {
    try {
      const { pageSize } = this.listViewStore;
      current = current || 1;
      Api.callApi(params).then(action((res) => {
        const { sessionkey } = res;
        Api.getDatas({
            dataKey: sessionkey,
            current,
            pageSize: pageSize,
          }).then(datares => {
          const { status, datas } = datares;
          if (status) {
						let fristData = [{
							id: '0',
							randomFieldId: '0',
							isDefault: '0',
							defaultValue: true,
							name: getLabel(501567, '默认不展现模板'),
							descriptionspan: getLabel(501568, '选择此项，写邮件时将不展现模板'),
						}];
            const newData = datas.map(d => ({ ...d, id: this.setId(d), randomFieldId: this.setId(d) }));
            const data = [...(current === 1 ? fristData : this.listViewStore.data), ...newData];
            let selectedRowKeys = data.filter(sign => sign.isDefault === '1').map(sign => sign.id);
            if (selectedRowKeys && selectedRowKeys.length === 0) { selectedRowKeys = ['0']; }
            const newState = {
              current,
              isTable: false,
              loading: false,
              haveCheck: true,
              selectedRowKeys,
              data,
            };
            this.listViewStore.setState(newState);
            this.listViewStore.updateDataSource();
          }
        });
        Api.getCounts({
            dataKey: sessionkey,
          }).then(countres => {
          if (countres.status) {
            this.listViewStore.setState({ hasMore: countres.count > current * pageSize});
          }
        });
      }));
    } catch (e) {
      Toast.info(e, 1);
    }
  }

  @action
  setId = (data) => {
    const { randomFieldId, templateType } = data;
    return `${templateType}_${randomFieldId}`;
  }

  @action
  getId = (id) => {
    return id && id.substring(id.lastIndexOf('_') + 1);
  }

  @action
  setState = (params = {}) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
    return this;
  }

  @action
  clear = () => this.setState(initState)
}
